angular.module('starter.controllers', [])

.controller('operateEssayCtl', ['$scope', '$location', '$routeParams', 'EssayService', '$http', function($scope, $location, $routeParams, EssayService, $http){	
	//sourceType 1 from create action, 2 from manageTag
	$scope.source_operate_essay_type = $routeParams.sourceType || 1;
	$scope.essay_id = $routeParams.id || 0;
	$scope.source.showCancelCreate = true;

	var initData = function(){
		if($scope.source_operate_essay_type == 1){
			var promise = EssayService.getEssay($scope.essay_id);
            promise.then(
                function(response){
                    if(response.data.status != 1){
	                    art.tip.danger("has error: " + response.data.message);
                    }
                    else{
						$scope.source.curEssay = response.data.essay;
						$scope.source.tagList = response.data.tags;
						$scope.source.categoryList = response.data.categories;
						
						$scope.source.curEssay.tags = [];
						if($scope.source.curEssay.tag_ids != ''){
							$.each($scope.source.curEssay.tag_ids.split(";"), function(index, item){
								$scope.source.curEssay.tags.push({
									id: item,
									title: $scope.source.curEssay.tag_titles.split(";")[index],
									color: $scope.source.curEssay.tag_colors.split(";")[index]
								});
							});
						}
                    }
                },
                function (error) {
                    art.tip.danger("service error status: " + error.status);
                }
            );
		}
	};


	$scope.manageStar = function(){
		$scope.source.curEssay.is_star = $scope.source.curEssay.is_star==0?1:0;
	};

	$scope.manageTag = function(){
		location.href = "#/operate-essay-manage-tag/2";
	};

    $scope.moveTag = function(elem, isAdd){
    	if(isAdd){
    		$scope.source.curEssay.tags.push(elem);
    	}
    	else{
    		$scope.source.curEssay.tags.splice($scope.source.curEssay.tags.indexOf(elem), 1);
    	}
    };

	$scope.submitEssay = function(){
		//add to db
		if(!$("#operateEssayForm").valid()){
			$(".alert-fn-valid").addClass("alert-danger")
				.html("You have some form errors. Please check below.");
			return false;
		}

		$.post("/essay/operate-essay-submit", $scope.source.curEssay, function(data){
			if(data.status != 1){
				art.tip.danger("submit error:" + data.message);
			}

			art.tip.success($scope.source.curEssay.id==0?"add essay success":"edit essay success");
			$scope.source.curEssay.id = data.result.id;
			if(typeof $scope.callback_submitEssay == "function"){
				$scope.callback_submitEssay($scope.curEssay);
			}
		});
	};

	$scope.$on('$viewContentLoaded', function() {  
        initData();   

        $('.form_datetime').datetimepicker({
			format:"yyyy-mm-dd hh:ii", 
			autoclose:true,
			startDate: new Date(),
			pickerPosition: "bottom-left"
		}).on("changeDate", function(ev){
			console.log(ev)
			operateEssayForm.element($("#postTime"));
		});

        validate.init();
		operateEssayForm = $("#operateEssayForm").validate({
			rules:{
				title: {
					"required":true,
					minlength:2
				},
				category: "required",
				content: {
					"required":true
				},
				postTime:{
					"required":true,
					date: true
				}
			}
		});
    });  
}])


.controller('operateTagCtl', ['$scope', '$location', '$routeParams', 'TagService', function($scope, $location, $routeParams, TagService){
    $scope.source.showCancelCreate = true;

	$scope.safeApply = function(fn) {
		var phase = this.$root.$$phase;
	 	if(phase == '$apply' || phase == '$digest') {
	 		if(fn && (typeof(fn) === 'function')) {
				fn();
			}
	 	}else {
			this.$apply(fn);
		}
	};

	$scope.source_operate_essay_type = $routeParams.sourceType || 1;  //1 normal  2 from essay
	$scope.tag_id = $routeParams.id || 0;
	var editTagForm;

	var initData = function(){
			$scope.curTag = {id:0, title:"", color:"#e11d21"};
		if($scope.source_operate_essay_type == 1){
			if($scope.tag_id != 0){
				var promise = TagService.getTagList({
					searchType: 0,
					searchCriteria:{
						id: $scope.tag_id
					}
				});
	            promise.then(
	                function(response){
	                    if(response.data.status != 1){
		                    art.tip.danger("has error: " + response.data.message);
	                    }
	                    else{
							$scope.curTag = response.data.result[0];						
	                    }
	                },
	                function (error) {
	                    art.tip.danger("service error status: " + error.status);
	                }
	            );				
			}
		}
	};

	$scope.changeColor = function(color){
		$scope.curTag.color = color;
		$('.colorpicker-default').colorpicker("setValue", color);
	}

	$scope.submitTag = function(){
		//add to db
		if(!$("#operateTagForm").valid()){
			$(".alert-fn-valid").addClass("alert-danger")
				.html("You have some form errors. Please check below.");
			return false;
		}

		$.post("/tag/operate-tag-submit", $scope.curTag, function(data){
			if(data.status != 1){
				art.tip.danger("submit error:" + data.message);
			}
			art.tip.success($scope.curTag.id==0?"add tag success":"edit tag success");
			$scope.curTag.id = data.result.id;
			if(typeof $scope.callback_submitTag == "function"){
				$scope.callback_submitTag($scope.curTag);
			}	
		});
	
	};
	
	$scope.$on('$viewContentLoaded', function() {  
        initData();

        $('.colorpicker-default').colorpicker()
        	.on('changeColor', function(ev){
        		//控件改变颜色的时候需要$apply
        		if($scope.curTag.color != ev.color.toHex()){
				  	$scope.safeApply(function(){$scope.curTag.color = ev.color.toHex();});
				}

				//出错以后改动color，改动以后让它验证下
				if($("#color").parent().parent().hasClass("has-error")){
					setTimeout(function(){operateTagForm.element($("#color"))}, 100);
				}
			}
		);

        validate.init();
		operateTagForm = $("#operateTagForm").validate({
			rules:{
				title: {
					"required":true,
					minlength:2
				},
				color:{
					"required":true,
					isColor: true
				}
			},
			errorClass: "error form-error"
		});

    });  
}])